package com.lou.simhasher.util;

import com.lou.simhasher.SimHasher;

import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;

/**
 * @Package: com.lou.simhasher.util
 * @Author: yanjiali
 * @Created: 2025/3/13 10:44
 * simhash比较类
 */
public class SimHashCompareUtil {

    /**
     * 获取两者的相似度比较结果值
     * @param simHasher
     * @param bigInteger
     * @return
     */
    public static int bothCompareValue(SimHasher simHasher, BigInteger bigInteger) {
        return simHasher.getHammingDistance(bigInteger);
    }

    /**
     * 通过字符串获取签名
     * @param text1
     * @return
     * @throws IOException
     */
    public static BigInteger getSignature(String text1) throws IOException {
        SimHasher simHasher = new SimHasher(text1);
        return simHasher.getSignature();
    }

    /**
     * 通过字符串获取SimHasher对象
     * @param text
     * @return
     * @throws IOException
     */
    public static SimHasher getSimHasher(String text) throws IOException {
        return new SimHasher(text);
    }

    /**
     * 通过字符串比较两者相似度
     * @param text1
     * @param text2
     * @return
     * @throws IOException
     */
    public static int useStringComeBothCompareValue(String text1, String text2) throws IOException {
        SimHasher simHasher1 = new SimHasher(text1);
        return bothCompareValue(simHasher1, getSignature(text2));
    }

    /**
     * 当前文章与已有的进行比较
     * @param text
     * @param signatureList
     * @return
     * @throws IOException
     */
    public static int CompareAll(String text, ArrayList<BigInteger> signatureList) throws IOException {
        if(text.trim().equals("") || text == null || signatureList.size() == 0 || signatureList == null) {
            throw new IllegalArgumentException("当前文章为无效或者传递的签名数组无效");
        }

        int minSimilarity = Integer.MAX_VALUE;
        SimHasher simHasher = getSimHasher(text);
        for(BigInteger signature : signatureList) {
            int temp = bothCompareValue(simHasher, signature);
            if(temp < minSimilarity) {
                minSimilarity = temp;
            }
        }

        return minSimilarity;
    }
}
